import { useMemberStore } from '@/stores'

const baseURL = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'
const httpInterceptor = {
  invoke(options: UniApp.RequestOptions) {
    if (!options.url.startsWith('http')) {
      options.url = baseURL + options.url
    }
    options.timeout = 10000
    options.header = {
      ...options.header,
      'source-client': 'minapp',
    }
    const memberStore = useMemberStore()
    const token = memberStore.profile?.token
    if (token) {
      options.header.Authorization = token
    }
  },
}
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)

// promise封装，以便后续调用直接await
// 泛型
interface Data<T> {
  code: string
  msg: string
  result: T
}

export const http = <T>(options: { method: string; url: string }) => {
  return new Promise<Data<T>>((resolve, reject) => {
    uni.request({
      ...options,
      success(data) {
        resolve(data.data as Data<T>)
      },
    })
  })
}
